package com.pig4cloud.pig.ads.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.feign.RemoteRoleGameService;
import com.pig4cloud.pig.ads.exception.CommentException;
import com.pig4cloud.pig.ads.pig.mapper.AdCommentMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdTermBannedMapper;
import com.pig4cloud.pig.ads.pig.mapper.TtAccesstokenMapper;
import com.pig4cloud.pig.ads.service.AdAccountService;
import com.pig4cloud.pig.ads.service.AdCommentService;
import com.pig4cloud.pig.ads.service.TtCommentApiService;
import com.pig4cloud.pig.api.dto.AdCommentDTO;
import com.pig4cloud.pig.api.dto.AdCommentOperateDto;
import com.pig4cloud.pig.api.dto.AdCommentStatisticsDTO;
import com.pig4cloud.pig.api.dto.OperateComment;
import com.pig4cloud.pig.api.entity.AdAccount;
import com.pig4cloud.pig.api.entity.AdCommentEntity;
import com.pig4cloud.pig.api.entity.AdTermBannedEntity;
import com.pig4cloud.pig.api.entity.TtAccesstoken;
import com.pig4cloud.pig.api.util.CommonConstants;
import com.pig4cloud.pig.api.vo.*;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.DateUtil;
import com.pig4cloud.pig.common.core.util.ECollectionUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class AdCommentServiceImpl extends ServiceImpl<AdCommentMapper, AdCommentEntity> implements AdCommentService {

	private static final ZoneOffset DONGBA_DISTRICT_OFFSET = ZoneOffset.ofHours(8);
	private static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").toFormatter();
	private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter();

	@Value("${pig_schema}")
	private String pigSchema;

	@Value("${3399_schema}")
	private String m3399Schema;

	@Value("${ch_3399_schema}")
	private String ch3399Schema;

	private final AdCommentMapper adCommentMapper;

//	private final AdCommentStatisticsMapper adCommentStatisticsMapper;

	private final TtCommentApiService ttCommentApiService;

	private final TtAccesstokenMapper ttAccesstokenMapper;

	//	private final AdvService advService;
	private final AdAccountService adAccountService;

	private final RemoteRoleGameService remoteRoleGameService;

	private final AdTermBannedMapper adTermBannedMapper;

	/**
	 * 更新评论是否包含屏蔽词
	 *
	 * @param param
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public void updateCommentTermsBanned(String param) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		log.info("===================更新评论是否包含屏蔽词任务开始=====================");
		Date startDay, endDay;
		String[] params;
		if (StringUtils.isNotBlank(param) && (params = param.split(",")).length > 0) {
			startDay = sdf.parse(params[0]);
			endDay = 2 == params.length ? sdf.parse(params[1]) : startDay;
		} else {
			LocalDateTime now = LocalDateTime.now();
			startDay = new Date(now.minusMonths(1).toInstant(DONGBA_DISTRICT_OFFSET).toEpochMilli());
			endDay = new Date(now.toInstant(DONGBA_DISTRICT_OFFSET).toEpochMilli());
		}
		// 获取所有屏蔽词
		List<AdTermBannedEntity> termBannedList = adTermBannedMapper.selectList(Wrappers.<AdTermBannedEntity>lambdaQuery().select(AdTermBannedEntity::getTerms, AdTermBannedEntity::getAdvertiserId).eq(AdTermBannedEntity::getIsDeleted, 0));
		Map<String, Set<String>> termsBannedMap = termBannedList.stream().collect(Collectors.groupingBy(AdTermBannedEntity::getAdvertiserId, Collectors.mapping(AdTermBannedEntity::getTerms, Collectors.toSet())));
		// 获取时间范围内的评论信息，由于rank是mysql关键字，所以这里单独处理
		List<AdCommentEntity> commentList = adCommentMapper.selectList(Wrappers.<AdCommentEntity>query().eq("`rank`", 1).lambda().select(AdCommentEntity::getId, AdCommentEntity::getText, AdCommentEntity::getAdvertiserId)
				.between(AdCommentEntity::getCreateDay, startDay, endDay).eq(AdCommentEntity::getIsDelete, 0));
		for (AdCommentEntity comment : commentList) {
			// 获取当前广告账户下的屏蔽词
			Set<String> termsSet = termsBannedMap.getOrDefault(comment.getAdvertiserId(), Collections.emptySet());
			// 判断是否包含屏蔽词
			String termsBanned = termsSet.stream().filter(terms -> comment.getText().contains(terms)).collect(Collectors.joining(","));
			LambdaUpdateWrapper<AdCommentEntity> update = Wrappers.<AdCommentEntity>lambdaUpdate().set(AdCommentEntity::getIsTermsBanned, termsBanned.length() > 0 ? 1 : 0).set(AdCommentEntity::getTermsBannedList, termsBanned)
					.set(AdCommentEntity::getUpdateDate, new Date()).eq(AdCommentEntity::getId, comment.getId());
			this.update(update);
		}

		log.info("=================更新评论是否包含屏蔽词任务结束=======================");
	}

	/**
	 * 评论统计分页列表
	 *
	 * @param req
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public Page<AdCommentStatisticsDTO> getCommentStatisticsPage(AdCommentStatisticsVO req) {
		Page<AdCommentStatisticsDTO> page = new Page<>();
		page.setCurrent(req.getCurrent()).setSize(req.getSize());
		AdCommentStatisticsDTO comment = new AdCommentStatisticsDTO().setOffset((int) req.offset()).setPageSize((int) req.getSize());

		// 获取当前用户拥有的广告账户
//		Set<String> advertiserIds = advService.getAccountList(Integer.parseInt(PlatformTypeEnum.TT.getValue()), null).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toSet());
		Set<String> advertiserIds = adAccountService.getAccountsByAuthorize(new AdAccountVo().setMediaCode(PlatformTypeEnum.TT.getValue())).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toSet());
		if (CollectionUtil.isEmpty(advertiserIds)) {
			// 当前帐户下没有广告账户
			return page.setTotal(0).setRecords(Collections.emptyList());
		}
		comment.setAdvertiserIds(advertiserIds);

		// 获取当前账户下子游戏信息
		List<Long> gameIds = Optional.ofNullable(remoteRoleGameService.getOwnerRoleGameIds()).map(R::getData).orElse(Collections.emptyList());
		if (gameIds.isEmpty()) {
			// 当前用户所属角色下没有子游戏
			return page.setTotal(0).setRecords(Collections.emptyList());
		}
		if (StringUtils.isNotEmpty(req.getGameidArr())) {
			gameIds = Optional.of(req.getGameidArr()).map(ECollectionUtil::stringToLongSet).orElse(Collections.emptySet()).stream().filter(gameIds::contains).collect(Collectors.toList());
			if (gameIds.isEmpty()) {
				return page.setTotal(0).setRecords(Collections.emptyList());
			}
		}
		comment.setGameIds(gameIds);

		// 构造查询条件
		comment.setSummaryType(req.getSummaryType()).setGroupBys(req.getGroupBys()).setStartTimeStr(req.getStartTimeStr()).setEndTimeStr(req.getEndTimeStr()).setMaterialId(req.getMaterialId()).setMaterialName(req.getMaterialName()).setCommentBlur(req.getCommentBlur());
		// 查询总数
		int total = 0;//adCommentStatisticsMapper.selectCommentStatisticsCount(pigSchema, m3399Schema, ch3399Schema, comment);
		// 查询分页列表
		List<AdCommentStatisticsDTO> entities = new ArrayList<>();//adCommentStatisticsMapper.selectCommentStatisticsList(pigSchema, m3399Schema, ch3399Schema, comment).stream().peek(e -> e.setPlatformId(1).setTermsBannedRatio(new BigDecimal(e.getTermsBannedCount() * 100).divide(new BigDecimal(e.getCommentCount()), 2, BigDecimal.ROUND_HALF_UP))).collect(Collectors.toList());
		return page.setTotal(total).setRecords(entities);
	}

	/**
	 * 获取评论列表
	 *
	 * @param comment
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public Page<AdCommentEntity> getCommentPage(AdCommentVo comment) {
		LambdaQueryWrapper<AdCommentEntity> commentQuery = Wrappers.<AdCommentEntity>lambdaQuery().eq(AdCommentEntity::getRank, 1)
				.eq(AdCommentEntity::getCreativeId, comment.getCreativeId()).eq(AdCommentEntity::getIsDelete, 0).orderByDesc(AdCommentEntity::getStick).orderByDesc(AdCommentEntity::getCreateTime);
		// 查询评论分页列表
		Page<AdCommentEntity> page = baseMapper.selectPage(new Page().setCurrent(comment.getCurrent()).setSize(comment.getSize()), commentQuery);
		if (page.getTotal() == 0) {
			return page;
		}
		page.getRecords().forEach(e -> e.setIdStr(String.valueOf(e.getId())));
		// 查询出所有的回复
		Set<Long> commentIds = page.getRecords().stream().map(AdCommentEntity::getId).collect(Collectors.toSet());
		LambdaQueryWrapper<AdCommentEntity> replyQuery = Wrappers.<AdCommentEntity>lambdaQuery()
				.select(AdCommentEntity::getId, AdCommentEntity::getUserScreenName, AdCommentEntity::getText, AdCommentEntity::getCreateTime, AdCommentEntity::getAdvertiserId, AdCommentEntity::getAdvertiserName,
						AdCommentEntity::getAdAccount, AdCommentEntity::getReplyCommentId, AdCommentEntity::getHide)
				.in(AdCommentEntity::getReplyCommentId, commentIds).eq(AdCommentEntity::getIsDelete, 0)
				.orderByDesc(AdCommentEntity::getCreateTime);
		List<AdCommentEntity> allReplyList = baseMapper.selectList(replyQuery).stream().peek(e -> e.setIdStr(String.valueOf(e.getId())).setReplyCommentIdStr(String.valueOf(e.getReplyCommentId()))).collect(Collectors.toList());
		// 将回复添加到评论列表
		for (AdCommentEntity cmt : page.getRecords()) {
			List<AdCommentEntity> replyList = new ArrayList<>();
			cmt.setReplyList(replyList);
			for (AdCommentEntity reply : allReplyList) {
				if (cmt.getId().equals(reply.getReplyCommentId())) {
					replyList.add(reply);
				}
			}
		}
		return page;
	}

	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public void commentReply(AdCommentVo comment) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long commentId = Long.parseLong(comment.getId());
		AdCommentEntity cmt = baseMapper.selectOne(Wrappers.<AdCommentEntity>lambdaQuery().select(AdCommentEntity::getAdId, AdCommentEntity::getAdName, AdCommentEntity::getCreativeId, AdCommentEntity::getReplyCount, AdCommentEntity::getAdvertiserId,
				AdCommentEntity::getAdvertiserName, AdCommentEntity::getAdAccount, AdCommentEntity::getReplyCommentId, AdCommentEntity::getRank).eq(AdCommentEntity::getId, commentId));
		if (null == cmt) {
			return;
		}
		if (cmt.getRank() == 1) {
			// 更新数据库
			this.update(Wrappers.<AdCommentEntity>lambdaUpdate().set(AdCommentEntity::getReplyCount, cmt.getReplyCount() + 1).set(AdCommentEntity::getReplyStatus, "REPLIED").set(AdCommentEntity::getUpdateDate, new Date()).eq(AdCommentEntity::getId, commentId));
			// 对评论进行回复
			TtAccesstoken token = ttAccesstokenMapper.selectById(cmt.getAdAccount());
			TtResultVo result = ttCommentApiService.reply(Long.parseLong(cmt.getAdvertiserId()), token.getAccessToken(), commentId, comment.getText(), null);
			JSONArray replyInfos;
			if (!result.getSuccess()) { // 调用失败
				log.error("评论回复接口调用失败=>评论id={},message={}", commentId, result.getMessage());
				throw new CommentException(CommonConstants.FAIL, result.getMessage());
			}
			if (CollectionUtils.isEmpty((replyInfos = result.getData().getJSONArray("reply_infos")))) {
				throw new CommentException(CommonConstants.FAIL, "媒体接口调用失败: reply_infos=NULL");
			}
			JSONObject reply = replyInfos.getJSONObject(0);
			Date now = new Date(), createTime = sdf.parse(reply.getString("create_time"));
			baseMapper.insert(new AdCommentEntity().setId(reply.getLong("id")).setUserScreenName("可爱的广告君").setAdId(cmt.getAdId()).setAdName(cmt.getAdName()).setText(reply.getString("text"))
					.setCreateTime(createTime).setCreateDay(createTime).setReplyStatus("NO_REPLY").setCreativeId(cmt.getCreativeId()).setRank(2).setAdvertiserId(cmt.getAdvertiserId()).setAdvertiserName(cmt.getAdvertiserName())
					.setAdAccount(cmt.getAdAccount()).setReplyCommentId(reply.getLong("reply_to_comment_id")).setCreateDate(now).setUpdateDate(now).setIsDelete(0).setHide(0));
		} else {
			// TODO: 对回复进行回复，目前不实现
//			result = ttCommentApiService.reply(Long.parseLong(cmt.getAdvertiserId()), token.getAccessToken(), cmt.getReplyCommentId(), text, commentId);
		}
	}

	/**
	 * 隐藏评论
	 *
	 * @param comment
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public void commentHide(AdCommentVo comment) {
		Long commentId = Long.parseLong(comment.getId());
		// 获取评论信息
		AdCommentEntity cmt = baseMapper.selectOne(Wrappers.<AdCommentEntity>lambdaQuery().select(AdCommentEntity::getHide, AdCommentEntity::getAdvertiserId, AdCommentEntity::getAdAccount).eq(AdCommentEntity::getId, commentId));
		if (null == cmt || 1 == cmt.getHide()) {
			return;
		}
		// 更新评论或回复数据
		this.update(Wrappers.<AdCommentEntity>lambdaUpdate().set(AdCommentEntity::getHide, 1).set(AdCommentEntity::getUpdateDate, new Date()).eq(AdCommentEntity::getId, commentId));
		// 隐藏评论
		TtAccesstoken token = ttAccesstokenMapper.selectById(cmt.getAdAccount());
		TtResultVo result = ttCommentApiService.hide(Long.valueOf(cmt.getAdvertiserId()), token.getAccessToken(), commentId);
		if (!result.getSuccess()) {//调用失败
			log.error("评论隐藏接口调用失败=>评论id:{},message:{}", commentId, result.getMessage());
			throw new CommentException(CommonConstants.FAIL, result.getMessage());
		}
	}

	/**
	 * 评论置顶操作
	 *
	 * @param comment
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public void commentStickOnTop(AdCommentVo comment) {
		Long commentId = Long.parseLong(comment.getId());
		// 获取评论信息
		AdCommentEntity cmt = baseMapper.selectOne(Wrappers.<AdCommentEntity>lambdaQuery().select(AdCommentEntity::getStick, AdCommentEntity::getCreativeId, AdCommentEntity::getAdvertiserId, AdCommentEntity::getAdAccount).eq(AdCommentEntity::getId, commentId));
		if (null == cmt || 1 == cmt.getStick()) {
			return;
		}
		// 将其他评论指定字段修改为0
		this.update(Wrappers.<AdCommentEntity>lambdaUpdate().set(AdCommentEntity::getStick, 0).set(AdCommentEntity::getUpdateDate, new Date()).eq(AdCommentEntity::getCreativeId, cmt.getCreativeId()).eq(AdCommentEntity::getStick, 1));
		// 将当前评论置顶字段修改为1
		this.update(Wrappers.<AdCommentEntity>lambdaUpdate().set(AdCommentEntity::getStick, 1).set(AdCommentEntity::getUpdateDate, new Date()).eq(AdCommentEntity::getId, commentId));
		// 调用头条接口
		TtAccesstoken token = ttAccesstokenMapper.selectById(cmt.getAdAccount());
		TtResultVo result = ttCommentApiService.stickOnTop(Long.parseLong(cmt.getAdvertiserId()), token.getAccessToken(), commentId);
		if (!result.getSuccess()) { // 调用失败
			log.error("评论置顶接口调用失败=>评论id:{},message:{}", commentId, result.getMessage());
			throw new CommentException(CommonConstants.FAIL, result.getMessage());
		}
	}

	/**
	 * 评论用户屏蔽
	 *
	 * @param comment
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public void commentBlockUsers(AdCommentVo comment) {
		Long commentId = Long.parseLong(comment.getId());
		// 获取评论信息
		AdCommentEntity cmt = baseMapper.selectOne(Wrappers.<AdCommentEntity>lambdaQuery().select(AdCommentEntity::getInBlackList, AdCommentEntity::getAdvertiserId, AdCommentEntity::getAdAccount).eq(AdCommentEntity::getId, commentId));
		if (null == cmt) {
			return;
		}
		// 将一级评论修改为屏蔽用户发表的评论，rank为mysql关键字，所以需要写sql
		this.update(Wrappers.<AdCommentEntity>update().set("in_black_list", 1).set("update_date", new Date()).eq("id", commentId).eq("`rank`", 1));

		// 调用头条接口
		TtAccesstoken token = ttAccesstokenMapper.selectById(cmt.getAdAccount());
		TtResultVo result = ttCommentApiService.blockUsers(Long.parseLong(cmt.getAdvertiserId()), token.getAccessToken(), commentId);
		if (!result.getSuccess()) { // 调用失败
			log.error("屏蔽用户接口调用失败=>评论id:{},message:{}", commentId, result.getMessage());
			throw new CommentException(CommonConstants.FAIL, result.getMessage());
		}

	}


	@Deprecated
	@Override
	public IPage<AdCommentVo> selectPageList(AdCommentDTO dto) {
		try {
			if (StringUtils.isNotBlank(dto.getEndTime())) {
				Date date = DateUtil.getDate(DateUtil.parse(dto.getEndTime().trim(), "yyyy-MM-dd"), 1);
				dto.setEndTime(DateUtil.formatDate(date, "yyyy-MM-dd"));
			}
		} catch (Exception e) {
			log.error("selectPageList formatDate  is error ", e);
		}
		Integer userId = SecurityUtils.getUser().getId();
		//获取当前账号下 广告账户列表
//		List<String> advertiserIds = advService.getOwnerAdv(userId, PlatformTypeEnum.TT.getValue());
		List<String> advertiserIds = adAccountService.getAccountsByAuthorize(new AdAccountVo().setMediaCode(PlatformTypeEnum.TT.getValue())).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(advertiserIds)) {
			return new Page();
		}
		dto.setAdvertiserIds(advertiserIds);
		return adCommentMapper.selectPageList(dto);
	}

	@Deprecated
	@Override
	public R commentReply(AdCommentOperateDto dto) {
		List<OperateComment> commentList = dto.getOperateComments();
		for (OperateComment operateComment : commentList) {
			TtAccesstoken token = ttAccesstokenMapper.selectById(operateComment.getAd_account());
			TtResultVo result = null;
			if (operateComment.getRank() > 1) {//二级评论
				//调用接口
				result = ttCommentApiService.reply(operateComment.getAdvertiser_id(), token.getAccessToken(), operateComment.getReply_comment_id(), dto.getText(), operateComment.getComment_id());
			} else {//一级评论
				//调用接口
				result = ttCommentApiService.reply(operateComment.getAdvertiser_id(), token.getAccessToken(), operateComment.getComment_id(), dto.getText(), null);
			}
			if (!result.getSuccess()) {//调用失败
				log.error("评论回复接口调用失败=>评论id:{},message:{}", operateComment.getComment_id(), result.getMessage());
				throw new CommentException(CommonConstants.FAIL, String.format("接口调用失败=>评论id:%s,%s", operateComment.getComment_id(), result.getMessage()));
			}
			//更新数据库
			adCommentMapper.updateReplyStatusById(operateComment.getComment_id(), "REPLIED");
		}
		return R.ok("", "操作成功");
	}

	@Deprecated
	@Override
	public R commentHide(AdCommentOperateDto dto) {
		List<OperateComment> commentList = dto.getOperateComments();
		AdCommentEntity updateComment = null;
		for (OperateComment operateComment : commentList) {
			TtAccesstoken token = ttAccesstokenMapper.selectById(operateComment.getAd_account());
			TtResultVo result = ttCommentApiService.hide(operateComment.getAdvertiser_id(), token.getAccessToken(), operateComment.getComment_id());
			if (!result.getSuccess()) {//调用失败
				log.error("评论隐藏接口调用失败=>评论id:{},message:{}", operateComment.getComment_id(), result.getMessage());
				throw new CommentException(CommonConstants.FAIL, String.format("接口调用失败=>评论id:%s,%s", operateComment.getComment_id(), result.getMessage()));
			}
			updateComment = new AdCommentEntity();
			updateComment.setId(operateComment.getComment_id());
			updateComment.setUpdateDate(new Date());
			updateComment.setHide(CommonConstants.HIDE_1);
			baseMapper.updateById(updateComment);

		}

		return R.ok("", "操作成功");
	}

	@Deprecated
	@Override
	public R commentStick(AdCommentOperateDto dto) {
		List<OperateComment> commentList = dto.getOperateComments();
		for (OperateComment operateComment : commentList) {
			TtAccesstoken token = ttAccesstokenMapper.selectById(operateComment.getAd_account());
			//调用接口
			TtResultVo result = ttCommentApiService.stickOnTop(operateComment.getAdvertiser_id(), token.getAccessToken(), operateComment.getComment_id());
			if (!result.getSuccess()) {//调用失败
				log.error("评论置顶接口调用失败=>评论id:{},message:{}", operateComment.getComment_id(), result.getMessage());
				throw new CommentException(CommonConstants.FAIL, String.format("接口调用失败=>评论id:%s,%s", operateComment.getComment_id(), result.getMessage()));
			}
			//更新数据库
			adCommentMapper.updateStickById(operateComment.getComment_id(), 1);//是否置顶，0：表示不置顶，1：表示置顶
		}
		return R.ok("", "操作成功");
	}

	/**
	 * 查询广告账号--广告组，-广告计划 树形结构
	 *
	 * @return
	 */
	@Override
	public R getCommentAdPlanTree(String name) {
//		Integer userId = SecurityUtils.getUser().getId();
		//获取当前账号下 广告账户列表
//		List<String> advertiserIds = advService.getOwnerAdv(userId, PlatformTypeEnum.TT.getValue());
		List<String> advertiserIds = adAccountService.getAccountsByAuthorize(new AdAccountVo().setMediaCode(PlatformTypeEnum.TT.getValue())).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(advertiserIds)) {
			return R.ok(null);
		}
		List<TtTreeVo> adTreeVoList = baseMapper.getCommentAdPlan(advertiserIds, name);

		return R.ok(adTreeVoList);
	}
}
